import React, { Component } from 'react'

export default class Chat extends Component {
  //声明状态
  state = {
    msgs: [
      'A',
      'B',
      'C'
    ],
    keyword: ''
  }

  //发送消息
  send = () => {
    //获取 input 框的输入值
    let {keyword, msgs} = this.state;
    //更新数组的状态
    this.setState({
      msgs: [...msgs, keyword]
    })
  }

  //渲染方法
  render() {
    return (
      <div>
        <input 
          type="text" 
          value={this.state.keyword} 
          onKeyUp={(e) => {
            //检测按下的按键是否为回车
            if(e.keyCode === 13){
              //更新状态
              this.setState({
                msgs: [...this.state.msgs, e.target.value],
                keyword: ''
              })
            }
          }}
          onChange={(e) => {
          this.setState({
            keyword: e.target.value
          })
        }} /><button onClick={this.send}>发送</button>
        <hr />
        <div id="result" ref={el => this.result = el} style={{width: '400px', overflowY: 'scroll' , height: '300px', border:'solid 1px #abc'}}>
          <ul>
            {
              this.state.msgs.map((item, index) => {
                return <li key={index}>{item}</li>
              })
            }
          </ul>
        </div>
      </div>
    )
  }

  //组件更新完成
  componentDidUpdate(){
    //获得result 元素
    this.result.scrollTop = this.result.scrollHeight;
  }

}
